<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Spinatiev Ivan
 * Date: 11/7/12
 * Time: 7:23 PM
 * To change this template use File | Settings | File Templates.
 */

class Page_Fe_Products_Step extends Page {
	/**
	 * @var Db_Products_Products
	 */
	protected $tableObject;

	function __construct() {
		self::$TPL->appendCssFile('wedding/step');
		self::$TPL->appendJsFile('wedding/step');
		self::$TPL->appendJsFile('wedding/problems_reported');

		parent::__construct();
	}

	public function defaultAction() {

		//data form from bestellung 2
		self::$S->Set('formData', $_POST);

		$sessionDelivery = self::$S->Get('delivery');
		self::$TPL->assign('sessionDelivery', $sessionDelivery);

		$memoryListProducts = Db_Products_MemoryListProducts::getMemoryProductsForStep(self::$S->Get('cart'));
		self::$TPL->assign('memoryListProducts', $memoryListProducts);

		$sessionCartList = self::$S->Get('cart');
		self::$TPL->assign('sessionCartList', $sessionCartList);
		//var_dump($memoryListProducts); exit;

		$productAnswer = Db_Products_Products::getAnswerProductForStep($sessionCartList);
		self::$TPL->assign('productAnswer', $productAnswer);

		$productEnvelopes = Db_Products_Products::getEnvelopesWithSameSize($sessionCartList);
		self::$TPL->assign('productEnvelopes', $productEnvelopes);
		//var_dump($productEnvelopes); exit;

        $productsWithSameStyle = Db_Products_Products::getProductsWithSameStylesForStep($sessionCartList);
		self::$TPL->assign('productsWithSameStyle', $productsWithSameStyle);

		$prices = Db_Products_Prices::getPricesForStep($sessionCartList);
		self::$TPL->assign('prices', $prices);

		$deliveryCountries = Db_Locale_ProjectCountriesDeliveryMethods::getCountriesDeliveryMethodsByProjectId(self::$PROJECT['id']);
		self::$TPL->assign('deliveryCountries', $deliveryCountries);
        if (!$prices || !$memoryListProducts || !$sessionCartList) {
			return array(
				'type' => 'redirect',
				'content' => '/'
			);
		}

		self::$TPL->setBodyTemplate('step');
		return array(
			'type' => 'display'
		);
	}

	public function saveProblemAction() {
		$reportedProblems = new Db_ReportedProblems();
		$reportedProblems->rp_user_ip = $_SERVER['REMOTE_ADDR'];
		$reportedProblems->rp_project_id = self::$PROJECT['id'];
		$reportedProblems->rp_type = post('type', 'str');
		$reportedProblems->rp_country = post('country', 'str');
		$reportedProblems->rp_city = post('city', 'str');
		$reportedProblems->rp_os_name = post('os_name', 'str');
		$reportedProblems->rp_email = post('email');
		$reportedProblems->rp_flash_version = post('flash_version', 'str');
		$reportedProblems->rp_memory_list_identifier = cookie(MEMORY_LIST_NAME_KEY);
		$reportedProblems->rp_phone = post('phone', 'str');
		$reportedProblems->rp_problem_content = post('problem_content', 'str');
		$reportedProblems->rp_screen_resolution = post('screen_width', 'int') . 'x' . post('screen_height', 'int');
		$reportedProblems->rp_session_id = session_id();
		$reportedProblems->rp_page = post('page', 'str');
		$reportedProblems->rp_browser = post('browser_name', 'str') . post('browser_version', 'str');
		if(!$reportedProblems->save()) {
			$this->error = true;
			$this->message = t(T_FORM_MSG, 'message_not_sent');
		}

		return array(
			'type' => 'encoded_json',
			'content' => $this->jsonResult($this->error, $this->message, !$this->error)
		);
	}

	public function removeFromCartAction() {
		$memoryId = get('memoryId', 'str');
		if ($memoryId) {
			$cart = self::$S->Get('cart');
			unset($cart[$memoryId]);
			self::$S->Set('cart', $cart);
		}
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}

	public function ajaxCounterAction() {
		$checkPrices = true;
		$sessionMemoryListProductId = array();
		$priceIdList = array();
		$isNotSamplePrice = 0;
		$result = post('counter_data');

		if($result['prices']) {
			$sessionCartList = self::$S->Get('cart');
			$productEnvelopes = Db_Products_Products::getEnvelopesWithSameSize($sessionCartList);
			foreach ($result['prices'] as $mlpId => $priceId) {
				$mlpIdDecode = Utils::memoryProductIdDecode($mlpId);
				$sessionMemoryListProductId[] = $mlpIdDecode;
				$priceIdList[] = $priceId;
			}
			$sizes = Db_Products_MemoryListProducts::getProductSizesByMemoryProductId($sessionMemoryListProductId);
			$samplePrices = Db_Products_Prices::getSamplePricesByPricesId($priceIdList);
			$memoryListProducts = Db_Products_MemoryListProducts::getMemoryProductsForStep(self::$S->Get('cart'));
			foreach ($result['prices'] as $mlpId => $priceId) {
				// Check price
				if (!$sessionCartList[$mlpId]['categoryId']) {
					$checkPrices = false;
				}
				if ($priceId == 'more_cards_' . $mlpId) {
					$priceWithMaxAmount = Db_Products_Prices::getPriceWithMaxAmount($sessionCartList[$mlpId]['categoryId'], $sizes[$mlpId]);
					if (!$priceWithMaxAmount  || $priceWithMaxAmount['am_amount'] >= $result['amount'][$mlpId]) {
						$checkPrices = false;
					} else {
						$priceId = $priceWithMaxAmount['price_id'];
					}
				} else {
					if (!Db_Products_Prices::checkPricesForStep($priceId, $sessionCartList[$mlpId]['categoryId'], $sizes[$mlpId], $result['amount'][$mlpId])) {
						$checkPrices = false;
					}
				}

				if ($checkPrices &&
					isset($productEnvelopes[Utils::memoryProductIdDecode($mlpId)]['product']['themes'][$result['envelope_theme_id'][$mlpId]]) &&
					isset($memoryListProducts[Utils::memoryProductIdDecode($mlpId)]["paper_types"][$result['paper_types_id'][$mlpId]])
				    ) {

					if (in_array($priceId, $samplePrices)) {
						unset($sessionCartList[$mlpId]['envelopeAmount']);
						unset($sessionCartList[$mlpId]['envelopeId']);
						unset($sessionCartList[$mlpId]['envelopeThemeId']);
						unset($sessionCartList[$mlpId]['envelopePriceId']);
					} else {
						$isNotSamplePrice = 1;
						$sessionCartList[$mlpId]['envelopeAmount'] = $result['envelope_amount'][$mlpId];
						$sessionCartList[$mlpId]['envelopeThemeId'] = $result['envelope_theme_id'][$mlpId];

						if (isset($productEnvelopes[Utils::memoryProductIdDecode($mlpId)]['product']['id']) && isset($productEnvelopes[Utils::memoryProductIdDecode($mlpId)]['price']['id'])) {
							$sessionCartList[$mlpId]['envelopeId'] = $productEnvelopes[Utils::memoryProductIdDecode($mlpId)]['product']['id'];
							$sessionCartList[$mlpId]['envelopePriceId'] = $productEnvelopes[Utils::memoryProductIdDecode($mlpId)]['price']['id'];
						}
					}
					$sessionCartList[$mlpId]['priceId'] = $priceId;
					$sessionCartList[$mlpId]['amount'] = $result['amount'][$mlpId];

					//$sessionCartList[$mlpId]['envelopeAmount'] = $result['envelope_amount'][$mlpId];
					//$sessionCartList[$mlpId]['envelopeId'] = $result['envelope_id'][$mlpId];
					//$sessionCartList[$mlpId]['envelopeThemeId'] = $result['envelope_theme_id'][$mlpId];
					//$sessionCartList[$mlpId]['amountMoreCards'] = $result['amount_more_cards'][$mlpId];
					//$sessionCartList[$mlpId]['envelopePriceId'] = $result['envelope_price_id'][$mlpId];
					$sessionCartList[$mlpId]['paperTypesId'] = $result['paper_types_id'][$mlpId];
				}

			}
			self::$S->Set('cart', $sessionCartList);

			$sessionDeliveryList = self::$S->Get('delivery');
            if ($isNotSamplePrice == 1) {
				$sessionDeliveryList['deliveryId'] = $result['delivery_id'];
			} else {
				unset($sessionDeliveryList['deliveryId']);
			}
			$sessionDeliveryList['countryId'] = $result['country_id'];
			self::$S->Set('delivery', $sessionDeliveryList);


		} else {
			$result = 0;
		}
		return array(
			'type' => 'json',
			'content' => $result
		);
	}


	public function ajaxDeliveryMethodsAction() {
		$sessionDeliveryList = self::$S->Get('delivery');
		$deliveryId = 0;

		$countryId = post('country_id', 'int');
		$changeCountry = post('change_country', 'int');
		if ($countryId) {
			$sessionDeliveryList['countryId'] = $countryId;
			if (isset($sessionDeliveryList['deliveryId'])) {
				$deliveryId = $sessionDeliveryList['deliveryId'];
			}

			if ($changeCountry  && $changeCountry == 1) {
				$deliveryId = 0;
			}

			$deliveryMethods = Db_Locale_ProjectCountriesDeliveryMethods::getDeliveryMethodsByProjectIdAndCountryId(self::$PROJECT['id'],$countryId );
			self::$TPL->assign('deliveryMethods', $deliveryMethods);
			self::$TPL->assign('deliveryId', $deliveryId);
			self::$S->Set('delivery', $sessionDeliveryList);

			return array(
				'type' => 'encoded_json',
				'content' => self::$TPL->display('delivery_methods', true)
			);
		} else {
			return array(
				'type' => 'json',
				'content' => 0
			);
		}
	}

	public function ajaxChangeEnvelopeAction() {
		$return = 1;
		if (post('mlp_id', 'string')) {
			$sessionCartList = self::$S->Get('cart');
			$sessionCartList[post('mlp_id', 'string')]['changeEnvelope'] = post('change_envelope_yes', 'int');
			$envelopeAmount = post('envelope_amount', 'int');
			if($envelopeAmount || $envelopeAmount == 0) {
				$sessionCartList[post('mlp_id', 'string')]['envelopeAmount'] = $envelopeAmount;
			}
			self::$S->Set('cart', $sessionCartList);
		} else {
			$return = 0;
		}
		return array(
			'type' => 'json',
			'content' => $return
		);
	}


	public function ajaxChangeEnvelopeThemeAction() {
		$return = 1;
		$mlpId = post('mlp_id', 'string');
		$themeId = post('theme_id', 'string');

		if ($mlpId && $themeId) {
			$sessionCartList = self::$S->Get('cart');
			$sessionCartList[$mlpId]['envelopeThemeId'] = $themeId;
			self::$S->Set('cart', $sessionCartList);
		} else {
			$return = 0;
		}
		return array(
			'type' => 'json',
			'content' => $return
		);
	}

	public function testForSessionAction() {

		$sessionCartList[Utils::memoryProductIdEncode(541)] = array(
			'productId' => Utils::memoryProductIdEncode(811),
			'themeId' => 61,
			'priceId' =>1308,
			'categoryId' => 1,
			'amount' => 20,
			'envelopeThemeId' => 131


		);

		$sessionCartList[Utils::memoryProductIdEncode(371)] = array(
			'productId' => Utils::memoryProductIdEncode(811),
			'themeId' => 71,
			'priceId' => 1308,
			'categoryId' => 1,
			'amount' => 20,
			'envelopeThemeId' => 131

		);


		self::$S->Set('cart', $sessionCartList);
		$sessionDelivery = array();

		 self::$S->Set('delivery', $sessionDelivery);

		//$memoryListProducts = Db_Products_MemoryListProducts::getMemoryProductsForStep($arrayCat);
		//$first = Db_Locale_ProjectCountriesDeliveryMethods::getDeliveryMethodsByProjectIdAndCountryId(self::$PROJECT['id'], 1);
		//$second = Db_Locale_ProjectCountriesDeliveryMethods::getDeliveryMethodsByProjectIdAndCountryId2(self::$PROJECT['id'], 1);

		//var_dump($first);
		//var_dump($second); exit;

	//	$deliveryCountries = Db_Locale_ProjectCountriesDeliveryMethods::getCountriesDeliveryMethodsByProjectId(self::$PROJECT['id']);

		//$result = Db_Locale_ProjectCountriesDeliveryMethods::getDeliveryMethodsByProjectIdAndCountryId(self::$PROJECT['id'],1 );
		/*$cart = self::$S->Get('cart');
        unset($cart['Rcxtbp']);
		self::$S->Set('cart', $cart);*/
		//self::$S->Remove('cart["Rcxtbp"]');


/*		self::$S->Set('formData', $_POST);
		echo "<pre>";
		print_r(self::$S->Get('formData'));
		echo "</pre>";
		exit;*/

		var_dump(self::$S->Get('cart'));
		var_dump(self::$S->Get('delivery'));

	}
}

